﻿using System;
using System.Text;
using System.Collections.Generic;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using ihongma.Common;
using System.Web.Script.Serialization;

namespace ihongma.Web.admin
{
    public partial class case_edit : ihongma.Web.UI.ManagePage
    {
        private string action = ActionEnum.Add.ToString(); //操作类型
        private int channel_id;
        private int id = 0;
        public string showtag;
        protected void Page_Load(object sender, EventArgs e)
        {
            string _action = DTRequest.GetQueryString("action");
            this.channel_id = DTRequest.GetQueryInt("channel_id");

            if (this.channel_id == 0)
            {
                JscriptMsg("频道参数不正确！", "back", "Error");
                return;
            }
            if (!string.IsNullOrEmpty(_action) && _action == ActionEnum.Edit.ToString())
            {
                this.action = ActionEnum.Edit.ToString();//修改类型
                this.id = DTRequest.GetQueryInt("id");
                if (this.id == 0)
                {
                    JscriptMsg("传输参数不正确！", "back", "Error");
                    return;
                }
                if (!new ihongma.BLL.webcase().Exists(this.id))
                {
                    JscriptMsg("信息不存在或已被删除！", "back", "Error");
                    return;
                }
            }
            if (!Page.IsPostBack)
            {
                //TreeBind(this.channel_id); //绑定类别
                //tagsPepeater.DataSource = new BLL.Tags().GetAllList();
                //tagsPepeater.DataBind();
              
                if (action == ActionEnum.Edit.ToString()) //修改
                {
                    ShowInfo(this.id);
                }
                //else
                //{
                //    LitAttributeList.Text = GetAttributeHtml(null, this.channel_id, this.id);
                //}
            }
        }

        #region 赋值操作=================================
        private void ShowInfo(int _id)
        {
            BLL.webcase bll = new BLL.webcase();
            Model.webcase model = bll.GetModel(_id);
           
           //ddlCategoryId.SelectedValue = model.category.ToString();
            txtTitle.Text = model.name;
            showid.Value = model.id.ToString();
            txtUrl.Text = model.weburl;
            if (model.is_top == 1)
            {
                cblItem.Items[0].Selected = true;
            }
            if (model.state == 1)
            {
                cblItem.Items[1].Selected = true;
            }


            txtclick.Text = model.click.ToString();
            txtContent.Value = model.describe;
            dianping.Value = model.dianping;
           
            //txtDiggAct.Text = model.digg_act.ToString();
            //txtContent.Value = model.content;
            //txtSeoTitle.Text = model.seo_title;
            //txtSeoKeywords.Text = model.seo_keywords;
            //txtSeoDescription.Text = model.seo_description;
            //赋值上传的相册
            
            tagslist.Text= GettagHtml(model.tags);
            colorlist.Text = GetcolorHTML(model.color);
            focus_photo.Value = model.img; //封面图片
            LitAlbumList.Text = GetAlbumHtml(model.Photolist, model.img);
            //赋值属性列表
           // LitAttributeList.Text = GetAttributeHtml(model.photo_attribute_values, this.channel_id, _id);
        }
        #endregion

        //#region 绑定类别=================================
        //private void TreeBind(int _channel_id)
        //{
        //    BLL.category bll = new BLL.category();
        //    DataTable dt = bll.GetList(0, _channel_id);

        //    this.ddlCategoryId.Items.Clear();
        //    this.ddlCategoryId.Items.Add(new ListItem("请选择类别...", ""));
        //    foreach (DataRow dr in dt.Rows)
        //    {
        //        string Id = dr["id"].ToString();
        //        int ClassLayer = int.Parse(dr["class_layer"].ToString());
        //        string Title = dr["title"].ToString().Trim();

        //        if (ClassLayer == 1)
        //        {
        //            this.ddlCategoryId.Items.Add(new ListItem(Title, Id));
        //        }
        //        else
        //        {
        //            Title = "├ " + Title;
        //            Title = Utils.StringOfChar(ClassLayer - 1, "　") + Title;
        //            this.ddlCategoryId.Items.Add(new ListItem(Title, Id));
        //        }
        //    }
        //}
        //#endregion
        private string GettagHtml(string age)
        {
           StringBuilder strtex = new StringBuilder();
           
            foreach (string str in age.Split(','))
            {
                Model.Tags model = new BLL.Tags().GetModel(int.Parse(str));
                strtex.Append("<div id=\"t"+model.id+"\">");
                strtex.Append("<li><a rel=\"tag\" href=\"javascript:void(0)\" >" + model.name + "");
                    strtex.Append("<input id=\"Hidden1\" type=\"hidden\" name=\"tags\" value=\""+model.id+"\" /></a></li>");
                    strtex.Append("<em  onclick=\"$('#t"+model.id+"').remove()\" style='cursor:pointer'>[X]</em>");
                    strtex.Append("</div>");
            }
            return strtex.ToString();

        }
        private string GetcolorHTML(string age)
        {
            StringBuilder strtex = new StringBuilder();
           
            foreach (string str in age.Split(','))
            {
               
                strtex.Append("<div id=\""+str+"\">");
                strtex.Append(" <span   class=\"color "+str+"\"  ><input id=\"Hidden1\" type=\"hidden\" name=\"color\" value=\""+ str + "\" /></span>");
                strtex.Append("<em onclick=\"$('#" +str + "').remove()\" style='cursor:pointer' >[X]</em>");
                strtex.Append("</div>");
            }
            return strtex.ToString();
        }
        #region 返回相册列表HMTL=========================
        private string GetAlbumHtml(List<Model.web_photo> models, string focus_photo)
        {
            StringBuilder strtag = new StringBuilder();
            JavaScriptSerializer java = new JavaScriptSerializer();

            StringBuilder strTxt = new StringBuilder();
           // strtag.Append("[");
            if (models != null)
            {
                foreach (Model.web_photo modelt in models)
                {
                    strTxt.Append("<li>\n");
                    strTxt.Append("<input type=\"hidden\" name=\"hide_photo_name\" value=\"" + modelt.id + "|" + modelt.big_img + "|" + modelt.small_img + "\" />\n");
                    strTxt.Append("<div class=\"photo-container\" ><img  id=\"photo" + modelt.id + "\" name=\"photo" + modelt.id + "\" bigsrc=\"" + modelt.small_img + "\"  src=\"" + modelt.big_img + "\"\n");
                    if (focus_photo == modelt.small_img)
                    {
                        strTxt.Append(" class=\"current\"\n");
                    }
                    strTxt.Append(" />\n</div>");
                    strTxt.Append("<br><a href=\"javascript:;\" onclick=focus_img(\"photo" + modelt.id + "\")>设置封面</a><a onclick=how_link(\"photo" + modelt.id + "\") href=\"javascript:;\">链接</a><a onclick=\"del_img(this);\" href=\"javascript:;\">删除</a>\n");
                    strTxt.Append("</li>\n");
                    strtag.Append("\"photo"+ modelt.id +"\":"+java.Serialize(modelt.Taglist).Replace("photoid\":","photoid\":\"photo").Replace("}","\"}")+",");
                }
            }
            showtag ="{"+strtag.ToString()+"}";
            if (showtag.EndsWith(",}"))
            {
                showtag = showtag.Remove(showtag.Length - 2, 1);
            }
            return strTxt.ToString();
        }
        #endregion

        //#region 返回属性列表HMTL=========================
        //private string GetAttributeHtml(List<Model.photo_attribute_value> models, int _channel_id, int _photo_id)
        //{
        //    StringBuilder strTxt = new StringBuilder();
        //    BLL.photo_attribute bll = new BLL.photo_attribute();
        //    DataSet ds = bll.GetList("channel_id=" + _channel_id);

        //    if (ds.Tables[0].Rows.Count > 0)
        //    {
        //        strTxt.Append("<tr><th>扩展属性：</th><td>\n");
        //        strTxt.Append("<table border=\"0\" cellspacing=\"0\" cellpadding=\"0\" class=\"border_table\">\n");
        //        strTxt.Append(" <tbody><col width=\"80px\"><col>\n");
        //        foreach (DataRow dr in ds.Tables[0].Rows)
        //        {
        //            int _value_id = 0;
        //            string _value_content = "";
        //            if (models != null)
        //            {
        //                foreach (Model.photo_attribute_value modelt in models)
        //                {
        //                    if (modelt.attribute_id == Convert.ToInt32(dr["id"]) && modelt.photo_id == _photo_id)
        //                    {
        //                        _value_id = modelt.id;
        //                        _value_content = modelt.content;
        //                    }
        //                }
        //            }
        //            strTxt.Append("<tr><th>" + dr["title"] + "</th><td>\n");
        //            strTxt.Append(GetAttributeType(Convert.ToInt32(dr["id"]), dr["title"].ToString(), dr["default_value"].ToString(), Convert.ToInt32(dr["type"]),
        //                _value_id, _value_content));
        //            strTxt.Append("</td></tr>\n");
        //        }
        //        strTxt.Append("</tbody>\n");
        //        strTxt.Append("</table>\n");
        //        strTxt.Append("</td></tr>\n");
        //    }
        //    return strTxt.ToString();
        //}
       // #endregion

       // #region 返回属性类型=============================
        ///// <summary>
        ///// 返回属性类型HTML
        ///// </summary>
        ///// <param name="_id">属性ID</param>
        ///// <param name="_title">属性标题</param>
        ///// <param name="_default_value">属性默认值</param>
        ///// <param name="_type">属性类型</param>
        ///// <param name="_value_id">属性值ID</param>
        ///// <param name="_value">属性值内容</param>
        ///// <returns>HTML代码</returns>
        //private string GetAttributeType(int _id, string _title, string _default_value, int _type, int _value_id, string _value)
        //{
        //    //分解默认值
        //    string[] valueArr = _default_value.Split(',');
        //    StringBuilder str = new StringBuilder();
        //    str.Append("<input type=\"hidden\" name=\"value_" + _id + "\" value=\"" + _value_id + "\"/>\n");
        //    switch (_type)
        //    {
        //        case (int)AttributeEnum.Text:
        //            if (_value_id > 0)
        //                _default_value = _value;
        //            str.Append("<input type=\"text\" name=\"content_" + _id + "\" value=\"" + _default_value + "\" class=\"txtInput middle\" />\n");
        //            break;
        //        case (int)AttributeEnum.Select:
        //            str.Append("<select name=\"content_" + _id + "\" class=\"select2\">\n");
        //            for (int i = 0; i < valueArr.Length; i++)
        //            {
        //                str.Append("<option value=\"" + valueArr[i] + "\"");
        //                if (_value_id > 0 && _value == valueArr[i])
        //                    str.Append(" selected");
        //                str.Append(">" + valueArr[i] + "</option>\n");
        //            }
        //            str.Append("</select>\n");
        //            break;
        //        case (int)AttributeEnum.Radio:
        //            for (int i = 0; i < valueArr.Length; i++)
        //            {
        //                str.Append("<label class=\"attr\"><input type=\"radio\" name=\"content_" + _id + "\" value=\"" + valueArr[i] + "\"");
        //                if (_value_id > 0 && _value == valueArr[i])
        //                    str.Append(" checked");
        //                str.Append("  />" + valueArr[i] + "</label>\n");
        //            }
        //            break;
        //        case (int)AttributeEnum.CheckBox:
        //            for (int i = 0; i < valueArr.Length; i++)
        //            {
        //                str.Append("<label class=\"attr\"><input type=\"checkbox\" name=\"content_" + _id + "\" value=\"" + valueArr[i] + "\"");
        //                if (_value_id > 0 && !string.IsNullOrEmpty(_value))
        //                {
        //                    string[] _valueArr = _value.Split(',');
        //                    for (int j = 0; j < _valueArr.Length; j++)
        //                    {
        //                        if (valueArr[i] == _valueArr[j])
        //                            str.Append(" checked");
        //                    }
        //                }
        //                str.Append(" />" + valueArr[i] + "</label>\n");
        //            }
        //            break;
        //    }
        //    return str.ToString();
        //}
        //#endregion

        #region 增加操作=================================
        private bool DoAdd()
        {
            bool result = true;
            ihongma.Model.webcase model = new Model.webcase();
            ihongma.BLL.webcase bll = new BLL.webcase();

            model.category = this.channel_id;
            model.name = txtTitle.Text.Trim();
            model.category =channel_id;
            model.describe =txtContent.Value;
            model.dianping = dianping.Value;
            model.weburl =txtUrl.Text;
            model.is_top = 0;
            model.state = 0;
            //model.is_hot = 0;
            //model.is_slide = 0;
            //model.is_lock = 0;
            if (cblItem.Items[0].Selected == true)
            {
                model.is_top = 1;
            }
            if (cblItem.Items[1].Selected == true)
            {
                model.state = 1;
            }
           
            //保存相册
            string[] albumArr = Request.Form.GetValues("hide_photo_name");
           
            if (albumArr != null && albumArr.Length > 0)
            {
                int temp =0;
                List<Model.web_photo> ls = new List<Model.web_photo>();
                for (int i = 0; i < albumArr.Length; i++)
                {
                    string[] imgArr = albumArr[i].Split('|');
                    if (imgArr.Length == 3)
                    {
                        
                        
                             temp = temp + 1;
                        
                        ls.Add(new Model.web_photo {Taglist=getlist(temp), big_img = imgArr[1], small_img = imgArr[2] });
                    }
                }
                model.Photolist = ls;
            }
            string[] tags = Request.Form.GetValues("tags");
            string img=string.Empty;
            foreach (var item in tags)
            {
                img = img + item + ",";
            }
            img = Utils.DelLastComma(img);
            model.tags = img;
            string[] color = Request.Form.GetValues("color");
            string str=string.Empty;
            foreach (var item in color)
            {
                str = str + item + ",";
            }
            str = Utils.DelLastComma(str);
            model.color = str;
            model.addtime = DateTime.Now.ToString();
            model.click =int.Parse(txtclick.Text);
            model.img = focus_photo.Value;
            //扩展属性
           

            if (bll.Add(model) < 1)
            {
                result = false;
            }
            return result;
        }
        private List<Model.tag> getlist(int i)
        {
           
            List<Model.tag> modellist=new List<Model.tag>();
            JavaScriptSerializer jserializer = new JavaScriptSerializer();
            string[] tag = Request.Form.GetValues("ptag"+i.ToString());
            if (tag != null && tag.Length > 0)
            {
                  for (int j = 0; j < tag.Length; j++)
                {
                    modellist.Add(jserializer.Deserialize<Model.tag>(tag[j]));
                }
            }
            return modellist;
        }
        #endregion

        #region 修改操作=================================
        private bool DoEdit(int _id)
        {
            bool result = true;
            ihongma.BLL.webcase bll = new BLL.webcase();
            ihongma.Model.webcase model =new Model.webcase();
            model.id =int.Parse(showid.Value);
            model.category = this.channel_id;
            model.name = txtTitle.Text.Trim();
            model.category = channel_id;
            model.describe = txtContent.Value;
            model.dianping = dianping.Value;
            model.weburl = txtUrl.Text;
            model.is_top = 0;
            model.state = 0;
            //model.is_hot = 0;
            //model.is_slide = 0;
            //model.is_lock = 0;
            if (cblItem.Items[0].Selected == true)
            {
                model.is_top = 1;
            }
            if (cblItem.Items[1].Selected == true)
            {
                model.state = 1;
            }
            string[] tags = Request.Form.GetValues("tags");
            string img = string.Empty;
            foreach (var item in tags)
            {
                img = img + item + ",";
            }
            img = Utils.DelLastComma(img);
            model.tags = img;
            string[] color = Request.Form.GetValues("color");
            string str = string.Empty;
            foreach (var item in color)
            {
                str = str + item + ",";
            }
            str = Utils.DelLastComma(str);
            model.color = str;
            model.addtime = DateTime.Now.ToString();
            model.click = int.Parse(txtclick.Text);
            model.img = focus_photo.Value;
            string[] albumArr = Request.Form.GetValues("hide_photo_name");

            if (albumArr != null && albumArr.Length > 0)
            {
                int temp = 0;
                List<Model.web_photo> ls = new List<Model.web_photo>();
                for (int i = 0; i < albumArr.Length; i++)
                {
                    string[] imgArr = albumArr[i].Split('|');
                    int img_id = int.Parse(imgArr[0]);
                    if (imgArr.Length == 3)
                    {
                        temp = img_id;
                        if (img_id < 0)
                            temp = temp + 1;
                        ls.Add(new Model.web_photo { Taglist =getlist(temp), id = img_id, photo_id = _id, big_img = imgArr[1], small_img = imgArr[2] });
                    }
                }
                model.Photolist = ls;
            }
          
            //if (model.photo_albums != null)
            //    model.photo_albums.Clear();
            //string[] albumArr = Request.Form.GetValues("hide_photo_name");
            //if (albumArr != null)
            //{
            //    List<Model.photo_album> ls = new List<Model.photo_album>();
            //    for (int i = 0; i < albumArr.Length; i++)
            //    {
            //        string[] imgArr = albumArr[i].Split('|');
            //        int img_id = int.Parse(imgArr[0]);
            //        if (imgArr.Length == 3)
            //        {
            //            ls.Add(new Model.photo_album { id = img_id, photo_id = _id, big_img = imgArr[1], small_img = imgArr[2] });
            //        }
            //    }
            //    model.photo_albums = ls;
            //}

          

            if (!bll.Update(model))
            {
                result = false;
            }
            return result;
        }
        #endregion

        //保存
        protected void btnSubmit_Click(object sender, EventArgs e)
        {
            if (action == ActionEnum.Edit.ToString()) //修改
            {
                ChkAdminLevel(channel_id, ActionEnum.Edit.ToString()); //检查权限
                if (!DoEdit(this.id))
                {
                    JscriptMsg("保存过程中发生错误啦！", "", "Error");
                    return;
                }
                JscriptMsg("修改图文成功啦！", "case_list.aspx?channel_id=" + this.channel_id, "Success");
            }
            else //添加
            {
                ChkAdminLevel(channel_id, ActionEnum.Add.ToString()); //检查权限
                if (!DoAdd())
                {
                    JscriptMsg("保存过程中发生错误啦！", "", "Error");
                    return;
                }
                JscriptMsg("添加图文成功啦！", "case_list.aspx?channel_id=" + this.channel_id, "Success");
            }
        }
    }
}